package com.bjesc_b2c.app.appraiset.mvp.view.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bjesc_b2c.app.appraiset.R;
import com.bjesc_b2c.app.appraiset.adapter.CheckedCarItemAdapter;
import com.bjesc_b2c.app.appraiset.base.BaseActivity;
import com.bjesc_b2c.app.appraiset.http.IApiActivityRequest;
import com.bjesc_b2c.app.appraiset.utils.AliYunUtils;
import com.bjesc_b2c.app.appraiset.utils.BitmapUtil;
import com.bjesc_b2c.app.appraiset.utils.CustomSharedPreferences;
import com.bjesc_b2c.app.appraiset.utils.GralleryFinalUtils;
import com.bjesc_b2c.app.appraiset.utils.RxGralleryFinalUtils;
import com.bjesc_b2c.app.appraiset.utils.TimeListUilts;
import com.bjesc_b2c.app.appraiset.widget.popupwindow.SelectPhotoPop;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.rxretrofit_build.CarPhotoID;
import com.rxretrofit_build.model.RxBusBean;
import com.rxretrofit_build.util.MapUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import app.pinggushi.bjesc.com.baserecyclerview.adapter.MultiItemTypeAdapter;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.finalteam.rxgalleryfinal.rxbus.event.ImageRadioResultEvent;
import master_bean.CheckedCarItemBean;
import master_bean.SinglePhotoUpBean;
import rx.Observable;
import rxretrofit_base.model.KeyBean;
import rxretrofit_base.model.ShowType;
import rxretrofit_base.model.TokenBean;
import rxretrofit_base.net.BaseSubscriber;
import rxretrofit_base.net.RxRequest;

import static android.view.View.GONE;

/**
 * Created by lenovo on 2017/2/24.
 * 骨架、装置可以跳进来的
 */

public class CarrosserieDescribeActivity extends BaseActivity implements MultiItemTypeAdapter.OnItemClickListener, CompoundButton.OnCheckedChangeListener {
    @InjectView(R.id.tv_title)
    TextView titleTv;
    @InjectView(R.id.cb_score_one)
    CheckBox scoreOneNameCb;
    @InjectView(R.id.cb_score_two)
    CheckBox scoreTwoNameCb;
    @InjectView(R.id.cb_score_three)
    CheckBox scoreThreeNameCb;
    @InjectView(R.id.cb_score_four)
    CheckBox scoreFourNameCb;
    @InjectView(R.id.edit_detail)
    EditText detailEdit;
    @InjectView(R.id.recycler_itemdetail_photo)
    RecyclerView photoRecycler;


    @InjectView(R.id.llty_score_one)
    LinearLayout scoreOneLlty;
    @InjectView(R.id.llty_score_two)
    LinearLayout scoreTwoLlty; @InjectView(R.id.llty_describe)
    LinearLayout describeLlty;


    private CheckedCarItemAdapter itemAdapter;
    private List<CheckedCarItemBean> photoBeanList;
    private SelectPhotoPop photoPop;
    private int currentIndex;

    private boolean isScore;
    private String title;
    private String scoreOneName;
    private String scoreTwoName;
    private String scoreThreeName;
    private String scoreFourName;
    private String sourceID;
    private String classID;
    private List<String> fileList;   //阿里文件名
    private String eStatusOne = "";
    private String eStatusTwo = "";
    private String eStatusThree = "";
    private String eStatusFour = "";
    private boolean isSave;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_carrosserie_describe);
        ButterKnife.inject(this);
        initTitle();
        getData();
    }

    private void getItemList(SinglePhotoUpBean data) {
        photoBeanList = new ArrayList<>();
        fileList = new ArrayList<>();
        if (data != null) {
            if (data.getImg_info() != null && data.getImg_info().size() > 0) {
                for (int i = 0; i < data.getImg_info().size(); i++) {
                    fileList.add(TimeListUilts.subUrl(data.getImg_info().get(i))); //将文件名添加到集合，以后需要用来删除的
                    photoBeanList.add(new CheckedCarItemBean(data.getImg_info().get(i), false));
                    //如果以后显示多张，这里需要判断最后一个，然后设置true
                }
            } else {
                photoBeanList.add(new CheckedCarItemBean("", false));
            }
            if (!TextUtils.isEmpty(data.getDescription())) {
                detailEdit.setText(data.getDescription());
            }
            if (data.getOption() != null) {
                eStatusOne = data.getOption().getE_one();
                eStatusTwo = data.getOption().getE_two();
                eStatusThree = data.getOption().getE_three();
                eStatusFour = data.getOption().getE_four();
            }
            if (!TextUtils.isEmpty(eStatusOne)) {
                scoreOneNameCb.setChecked(true);
            }
            if (!TextUtils.isEmpty(eStatusTwo)) {
                scoreTwoNameCb.setChecked(true);
            }
            if (!TextUtils.isEmpty(eStatusThree)) {
                scoreThreeNameCb.setChecked(true);
            }
            if (!TextUtils.isEmpty(eStatusFour)) {
                scoreFourNameCb.setChecked(true);
            }
        } else {
            photoBeanList.add(new CheckedCarItemBean("", false));
        }
        initViews();
    }

    private void initViews() {
        photoPop = new SelectPhotoPop(this, popListener);
        photoRecycler.setLayoutManager(new GridLayoutManager(this, 3, LinearLayoutManager.VERTICAL, false));
        itemAdapter = new CheckedCarItemAdapter(this, R.layout.layout_item_car_surface_item_detail, photoBeanList);
        photoRecycler.setAdapter(itemAdapter);
        itemAdapter.setOnItemClickListener(this);
        scoreOneNameCb.setOnCheckedChangeListener(this);
        scoreTwoNameCb.setOnCheckedChangeListener(this);
        scoreThreeNameCb.setOnCheckedChangeListener(this);
        scoreFourNameCb.setOnCheckedChangeListener(this);
    }

    private void initTitle() {
        title = getIntent().getStringExtra("title");
        if (!TextUtils.isEmpty(title)) {
            titleTv.setText(title);
        }
        isScore = getIntent().getBooleanExtra("isScore", false);
        scoreOneName = getIntent().getStringExtra("scoreOneName");
        scoreTwoName = getIntent().getStringExtra("scoreTwoName");
        scoreThreeName = getIntent().getStringExtra("scoreThreeName");
        scoreFourName = getIntent().getStringExtra("scoreFourName");
        sourceID = getIntent().getStringExtra("sourceID");
        classID = getIntent().getStringExtra("classID");

        if (isScore) {        //如果需要评分，就显示，然后挨个去判断
            scoreOneLlty.setVisibility(View.VISIBLE);
            scoreTwoLlty.setVisibility(View.VISIBLE);

            if (!TextUtils.isEmpty(scoreOneName)) {
                scoreOneNameCb.setText(scoreOneName);
            }
            if (!TextUtils.isEmpty(scoreTwoName)) {
                scoreTwoNameCb.setText(scoreTwoName);
            } else {
                scoreTwoNameCb.setVisibility(View.INVISIBLE);
            }
            if (!TextUtils.isEmpty(scoreThreeName)) {
                scoreThreeNameCb.setText(scoreThreeName);
                scoreTwoLlty.setVisibility(View.VISIBLE);
            } else {
                scoreTwoLlty.setVisibility(GONE);
            }
            if (!TextUtils.isEmpty(scoreFourName)) {
                scoreFourNameCb.setText(scoreFourName);
                scoreFourNameCb.setVisibility(View.VISIBLE);
            } else {
                scoreFourNameCb.setVisibility(View.INVISIBLE);
            }

        } else {//没有评分就隐藏
            scoreOneLlty.setVisibility(GONE);
            scoreTwoLlty.setVisibility(GONE);
        }

        if(CarPhotoID.surfaceID.equals(classID)){
            describeLlty.setVisibility(GONE);
        }else{
            describeLlty.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

        switch (compoundButton.getId()) {
            case R.id.cb_score_one:
                if (b) {
                    eStatusOne = judgmentMultipleChoice(eStatusOne, scoreOneNameCb.getText().toString());
                } else {
                    eStatusOne = "";
                }
                break;
            case R.id.cb_score_two:
                if (b) {
                    eStatusTwo = judgmentMultipleChoice(eStatusTwo, scoreTwoNameCb.getText().toString());
                } else {
                    eStatusTwo = "";
                }
                break;
            case R.id.cb_score_three:
                if (b) {
                    eStatusThree = judgmentMultipleChoice(eStatusThree, scoreThreeNameCb.getText().toString());
                } else {
                    eStatusThree = "";
                }
                break;
            case R.id.cb_score_four:
                if (b) {
                    eStatusFour = judgmentMultipleChoice(eStatusFour, scoreFourNameCb.getText().toString());
                } else {
                    eStatusFour = "";
                }
                break;
        }
    }


    /**
     * 判断多选
     */
    private String judgmentMultipleChoice(String text, String status) {
        switch (status) {
            case "异响":
                text = "1";
                break;
            case "升降故障":
                text = "2";
                break;
            case "故障":
                text = "3";
                break;
            case "转向灯故障":
                text = "4";
                break;
            case "大灯故障":
                text = "5";
                break;
            case "阅读灯故障":
                text = "6";
                break;
            case "雾灯故障":
                text = "7";
                break;
            case "压缩机故障":
                text = "8";
                break;
            case "鼓风机故障":
                text = "9";
                break;
            case "水箱曾修复":
                text = "10";
                break;
            case "水箱曾更换":
                text = "11";
                break;
            case "尾气异常":
                text = "12";
                break;
            case "启动异常":
                text = "13";
                break;
            case "弹射":
                text = "14";
                break;
            case "漏油":
                text = "15";
                break;
            case "故障灯":
                text = "16";
                break;
            case "仪表指正故障":
                text = "17";
                break;
            case "音频故障":
                text = "18";
                break;
            case "视频故障":
                text = "19";
                break;
            case "按钮失灵":
                text = "20";
                break;
            case "按钮破损":
                text = "21";
                break;
            case "破损":
                text ="22";
                break;
            case "划伤":
                text = "23";
                break;
            case "曾更换":
                text = "24";
                break;
        }
        return text;
    }

    @OnClick({R.id.iv_return, R.id.tv_save_info, R.id.tv_reset})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_return:
                onBackPressed();
                break;
            case R.id.tv_save_info:
                saveImg();
                break;
            case R.id.tv_reset:
                reset();
                break;
        }
    }

    private void reset() {
        eStatusOne = "";
        eStatusTwo = "";
        eStatusThree = "";
        eStatusFour = "";
        scoreOneNameCb.setChecked(false);
        scoreTwoNameCb.setChecked(false);
        scoreThreeNameCb.setChecked(false);
        scoreFourNameCb.setChecked(false);
    }

    private void saveImg() {
        SinglePhotoUpBean bean = new SinglePhotoUpBean();
        bean.setImg_info(getUpLoadImgList());
        bean.setAttr_id(sourceID);
        bean.setDescription(detailEdit.getText().toString());
        bean.setOption(getOption());
        bean.setId(CustomSharedPreferences.getString(this, KeyBean.CARID.valueOf(), KeyBean.FILE_NAME.valueOf()));
        HashMap<String, Object> build = new MapUtil()
                .put("data", new Gson().toJson(bean))
                .build();
        Observable<TokenBean> tokenBeanObservable = null;
        if (classID.equals(CarPhotoID.frameworkID)) { //判断是哪个分类的

            tokenBeanObservable = RxRequest.getClient(this, build).create(IApiActivityRequest.class).saveFrame();
        } else if (classID.equals(CarPhotoID.deviceID)) {

            tokenBeanObservable = RxRequest.getClient(this, build).create(IApiActivityRequest.class).saveDevice();
        }else if(classID.equals(CarPhotoID.surfaceID)){
            tokenBeanObservable = RxRequest.getClient(this, build).create(IApiActivityRequest.class).saveSurface();
        }

        RxRequest.request(ShowType.SHOW, tokenBeanObservable
                , new BaseSubscriber<TokenBean>(this) {
                    @Override
                    public void onSuccess(TokenBean o) {
                        Intent intent = new Intent();
                        intent.putExtra("sourceID", sourceID);
                        intent.putExtra("isChange", true);
                        if(!TextUtils.isEmpty(eStatusOne)){
                            intent.putExtra("color", "yellow");
                        }else if(!TextUtils.isEmpty(eStatusTwo)){
                            intent.putExtra("color", "yellow");
                        }else if(!TextUtils.isEmpty(eStatusThree)){
                            intent.putExtra("color", "yellow");
                        }
                        setResult(0, intent);
                        finish();
                    }

                    @Override
                    public void onFailure(Throwable e) {

                    }
                });
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        if (!isSave) {
            intent.putExtra("sourceID", sourceID);
            intent.putExtra("isChange", false);
            intent.putExtra("color", "green");
        }
        setResult(0, intent);
        finish();
    }


    /**
     * 设置选项
     *
     * @return
     */
    private SinglePhotoUpBean.Option getOption() {
        SinglePhotoUpBean.Option option = new SinglePhotoUpBean.Option();
        option.setE_one(eStatusOne);
        option.setE_two(eStatusTwo);
        option.setE_three(eStatusThree);
        option.setE_four(eStatusFour);

        return option;
    }

    /**
     * 将图片存到一个集合里面准备上传,并且提交到阿里云
     *
     * @return
     */
    private List<String> getUpLoadImgList() {
        List<String> photoList = new ArrayList<>();
        for (int i = 0; i < photoBeanList.size(); i++) {    //循环上传图片到阿里
            if (!TextUtils.isEmpty(photoBeanList.get(i).getPhoto())) {
                if (!photoBeanList.get(i).getPhoto().contains("http")) {
                    String fileName = TimeListUilts.getObjectKey() + ".png";
                    AliYunUtils.aLiYunUpLoadFuncation(
                            this,
                            sourceID,       //图片ID
                            fileName,                           //图片名
                            photoBeanList.get(i).getPhoto()     //图片路径
                            , null);

                    photoList.add(fileName);
                } else {
                    photoList.add(TimeListUilts.subUrl(photoBeanList.get(i).getPhoto()));
                }
            }
        }
        return photoList;
    }

    private View.OnClickListener popListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.rlty_select_camera:     //选择相机
                    GralleryFinalUtils.openCamera(gralleryCallBack);
                    break;
                case R.id.rlty_select_album:    //选择相册
                    RxGralleryFinalUtils.openRadioImage(CarrosserieDescribeActivity.this, rxGalleryCallBack);
                    break;
            }
            if (photoPop.isShowing()) {
                photoPop.dismiss();
            }
        }
    };


    private RxGralleryFinalUtils.RxGalleryFinalCallBack rxGalleryCallBack = new RxGralleryFinalUtils.RxGalleryFinalCallBack() {
        @Override
        public void onEvent(ImageRadioResultEvent imageRadioResultEvent) {
            Logger.d("currentIndex--->>"+currentIndex);
            Bitmap bitmap = BitmapUtil.getBitmapFromSDCard(imageRadioResultEvent.getResult().getOriginalPath());
            Logger.d("bitmap ->"+bitmap.getWidth());
            Logger.d("bitmap ->"+bitmap.getHeight());
            Bitmap sbitmap1 = BitmapUtil.storeImage(bitmap,900,1200);
            Logger.d("sbitmap1 ->"+sbitmap1.getWidth());
            Logger.d("sbitmap1 ->"+sbitmap1.getHeight());

            BitmapUtil.saveBitmapToLocal(sbitmap1,imageRadioResultEvent.getResult().getOriginalPath());

            refreshImage(imageRadioResultEvent.getResult().getOriginalPath(), currentIndex);
        }
    };

    private GalleryFinal.OnHanlderResultCallback gralleryCallBack = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
            if (reqeustCode == GralleryFinalUtils.CAMERA) {
               Logger.d("currentIndex--->>"+currentIndex);
                Bitmap bitmap = BitmapUtil.getBitmapFromSDCard(resultList.get(0).getPhotoPath());
                Logger.d("bitmap ->"+bitmap.getWidth());
                Logger.d("bitmap ->"+bitmap.getHeight());
                Bitmap sbitmap1 = BitmapUtil.storeImage(bitmap,900,1200);
                Logger.d("sbitmap1 ->"+sbitmap1.getWidth());
                Logger.d("sbitmap1 ->"+sbitmap1.getHeight());

                BitmapUtil.saveBitmapToLocal(sbitmap1,resultList.get(0).getPhotoPath());

                refreshImage(resultList.get(0).getPhotoPath(), currentIndex);
            }
        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {

        }
    };

    protected void refreshImage(String url, int index) {
        photoBeanList.set(index, new CheckedCarItemBean(url, true));
        itemAdapter.notifyDataSetChanged();
    }


    @Override
    public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
        currentIndex = position;
        if (TextUtils.isEmpty(photoBeanList.get(position).getPhoto())) {
            //跳转相机
            photoPop.showAtLocation(this.findViewById(R.id.llty_root), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        } else {
            //跳转大图
            Intent bigIntent = new Intent(CarrosserieDescribeActivity.this, BigCarSourcePhotoActivity.class);
            bigIntent.putExtra("classId", classID);
            bigIntent.putExtra("sourceId", sourceID);
            bigIntent.putExtra("title", title);
            bigIntent.putExtra("photoUrl", photoBeanList.get(position).getPhoto());
            if (fileList != null && fileList.size() > 0) {
                bigIntent.putExtra("fileName", TimeListUilts.subUrl(photoBeanList.get(position).getPhoto()));
            }
            bigIntent.putExtra("isSave", isSave);
            startIntent(bigIntent, 26);
        }
    }

    @Override
    protected void doOnNext(RxBusBean rxBusBean) {
        super.doOnNext(rxBusBean);
        if (rxBusBean.getRequestMark().equals(sourceID)) {
            if (!TextUtils.isEmpty(photoBeanList.get(currentIndex).getPhoto())) {
                photoBeanList.set(currentIndex, new CheckedCarItemBean("", false));
            }
            itemAdapter = new CheckedCarItemAdapter(this, R.layout.layout_item_car_surface_item_detail, photoBeanList);
            itemAdapter.setOnItemClickListener(this);
            photoRecycler.setAdapter(itemAdapter);
        }
    }

    @Override
    public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
        return false;
    }

    private void getData() {
        HashMap<String, Object> build = new MapUtil()
                .put("id", CustomSharedPreferences.getString(this, KeyBean.CARID.valueOf(), KeyBean.FILE_NAME.valueOf()))
                .put("class_id", classID)
                .put("attr_id", sourceID)
                .build();
        RxRequest.request(ShowType.SHOW, RxRequest.getClient(this, build).create(IApiActivityRequest.class).getSinglePhoto()
                , new BaseSubscriber<TokenBean<SinglePhotoUpBean>>(this) {
                    @Override
                    public void onSuccess(TokenBean<SinglePhotoUpBean> o) {
                        if (o.getStatus_code() == 9) {
                            isSave = false;
                        } else if (o.getStatus_code() == 0) {
                            isSave = true;
                        }
                        getItemList(o.getData());
                    }

                    @Override
                    public void onFailure(Throwable e) {

                    }
                });
    }


}
